package com.jfs.qy.config;

import com.jfs.qy.config.component.SSLSocketClient;
import com.jfs.qy.properties.OkHttpProperties;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.TimeUnit;

/**
 * @Description okhttp 配置类
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022/11/5
 */
@Configuration
@EnableConfigurationProperties(value = {OkHttpProperties.class})
public class OkHttpConfig {

    /**
     * 配置okhttp 客户端
     * @param okHttpProperties
     * @return
     */
    @Bean
    public OkHttpClient okHttpConfigClient(OkHttpProperties okHttpProperties) {

        return new OkHttpClient().newBuilder()
                //配置忽略ssl
                .sslSocketFactory(SSLSocketClient.getSSLSocketFactory(), SSLSocketClient.getX509TrustManager())
                .hostnameVerifier(SSLSocketClient.getHostnameVerifier())
                .connectionPool(pool(okHttpProperties))
                .connectTimeout(okHttpProperties.getConnectTimeout(), TimeUnit.SECONDS)
                .readTimeout(okHttpProperties.getReadTimeout(), TimeUnit.SECONDS)
                .writeTimeout(okHttpProperties.getWriteTimeout(), TimeUnit.SECONDS)
                .hostnameVerifier((hostname, session) -> true)
                .build();
    }

    /**
     * 配置连接池
     * @param okHttpProperties
     * @return
     */
    @Bean
    public ConnectionPool pool(OkHttpProperties okHttpProperties) {
        return new ConnectionPool(okHttpProperties.getMaxIdleConnections(), okHttpProperties.getKeepAliveDuration(), TimeUnit.SECONDS);
    }

}
